package com.boang.jdbc;

import com.boang.util.DbUtil;

import java.sql.*;

/*
  @author: 13813
  @date: 2024/12/9 17:07
*/
public class JdbcDemo03 {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Connection connection = null;
        try {
            //开启事务
//            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db62", "root", "123456");
            connection = DbUtil.getConn();
            connection.setAutoCommit(false); //开启事务
            int claId = addCla("74期", connection);
            Student student = new Student("明明", claId);
            addStu(student, connection);
            //提交
            connection.commit();
        } catch (SQLException e) {
            //回滚
            connection.rollback();
        } finally {
            connection.close();
        }
    }

    private static int addStu(Student student, Connection connection) throws SQLException, ClassNotFoundException {
        int n = 1 / 0;
        //增 班级表
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement("insert into student(name,cla_id)values(?,?)");
            preparedStatement.setString(1, student.getName());
            preparedStatement.setInt(2, student.getClaId());
            int i = preparedStatement.executeUpdate();
            return 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            preparedStatement.close();
        }
    }

    private static int addCla(String name, Connection connection) throws SQLException, ClassNotFoundException {
        //增 班级表
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement("insert into cla(name)values(?)");
            preparedStatement.setString(1, name);
            int i = preparedStatement.executeUpdate();

            PreparedStatement prepared = connection.prepareStatement("select last_insert_id()");
            resultSet = prepared.executeQuery();

            while (resultSet.next()) {
                int claId = resultSet.getInt(1);
                return claId;
            }
            return 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            resultSet.close();
            preparedStatement.close();
        }
    }
}
